package com.ruoyi.fun.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcStockLog;
import com.ruoyi.fun.service.IEcStockLogService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 库存记录Controller
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@RestController
@RequestMapping("/fun/log")
public class EcStockLogController extends BaseController
{
    @Autowired
    private IEcStockLogService ecStockLogService;

    /**
     * 查询库存记录列表
     */
    @PreAuthorize("@ss.hasPermi('fun:log:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcStockLog ecStockLog)
    {
        startPage();
        // 添加组织过滤，只显示当前组织的库存记录
        Long currentOrgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (currentOrgId != null && currentOrgId == 103L) {
            currentOrgId = null;
        }
        System.out.println("=== EcStockLogController.list 调试信息 ===");
        System.out.println("当前用户ID: " + getUserId());
        System.out.println("当前部门ID: " + getDeptId());
        System.out.println("当前组织ID: " + currentOrgId);
        System.out.println("传入的查询参数orgId: " + ecStockLog.getOrgId());
        
        ecStockLog.setOrgId(currentOrgId);
        System.out.println("设置后的查询参数orgId: " + ecStockLog.getOrgId());
        
        List<EcStockLog> list = ecStockLogService.selectEcStockLogList(ecStockLog);
        System.out.println("查询结果数量: " + list.size());
        
        return getDataTable(list);
    }

    /**
     * 导出库存记录列表
     */
    @PreAuthorize("@ss.hasPermi('fun:log:export')")
    @Log(title = "库存记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcStockLog ecStockLog)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        ecStockLog.setOrgId(orgId);
        List<EcStockLog> list = ecStockLogService.selectEcStockLogList(ecStockLog);
        ExcelUtil<EcStockLog> util = new ExcelUtil<EcStockLog>(EcStockLog.class);
        util.exportExcel(response, list, "库存记录数据");
    }

    /**
     * 获取库存记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:log:query')")
    @GetMapping(value = "/{logId}")
    public AjaxResult getInfo(@PathVariable("logId") Long logId)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        return success(ecStockLogService.selectEcStockLogByLogIdAndOrgId(logId, orgId));
    }

    /**
     * 新增库存记录
     */
    @PreAuthorize("@ss.hasPermi('fun:log:add')")
    @Log(title = "库存记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcStockLog ecStockLog)
    {
        ecStockLog.setOrgId(getOrgId());
        return toAjax(ecStockLogService.insertEcStockLog(ecStockLog));
    }

    /**
     * 修改库存记录
     */
    @PreAuthorize("@ss.hasPermi('fun:log:edit')")
    @Log(title = "库存记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcStockLog ecStockLog)
    {
        return toAjax(ecStockLogService.updateEcStockLog(ecStockLog));
    }

    /**
     * 删除库存记录
     */
    @PreAuthorize("@ss.hasPermi('fun:log:remove')")
    @Log(title = "库存记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{logIds}")
    public AjaxResult remove(@PathVariable Long[] logIds)
    {
        return toAjax(ecStockLogService.deleteEcStockLogByLogIds(logIds));
    }

    /**
     * 导入库存记录数据
     */
    @Log(title = "库存记录", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam(value = "updateSupport", defaultValue = "false") boolean updateSupport) throws Exception
    {
        ExcelUtil<EcStockLog> util = new ExcelUtil<EcStockLog>(EcStockLog.class);
        List<EcStockLog> logList = util.importExcel(file.getInputStream());
        
        // 预处理Excel解析后的数据，转换中文操作类型为数值
        for (EcStockLog log : logList) {
            // 转换操作类型：入库->1, 出库->2, 调整->3
            if (log.getOperationType() != null) {
                String operationType = log.getOperationType().trim();
                switch (operationType) {
                    case "入库":
                        log.setOperationType("1");
                        break;
                    case "出库":
                        log.setOperationType("2");
                        break;
                    case "调整":
                        log.setOperationType("3");
                        break;
                    default:
                        // 如果不是中文，保持原值
                        break;
                }
            }
        }
        
        String operName = getUsername();
        Long orgId = getOrgId();
        String message = ecStockLogService.importStockLog(logList, updateSupport, operName, orgId);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<EcStockLog> util = new ExcelUtil<EcStockLog>(EcStockLog.class);
        util.importTemplateExcel(response, "库存记录数据");
    }
    /**
     * 根据logId和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:ecstocklog:query')")
    @GetMapping(value = "/{logId}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("logId") Long logId, @PathVariable("orgId") Long orgId)
    {
        return success(ecStockLogService.selectEcStockLogByLogIdAndOrgId(logId, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('fun:ecstocklog:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcStockLog ecStocklog = new EcStockLog();
        List<EcStockLog> list = ecStockLogService.selectEcStockLogListByOrgId(ecStocklog, orgId);
        return getDataTable(list);
    }


}